package cn.bytets.rpc.api.headler;

import cn.bytets.rpc.common.thread.NamedThreadFactory;
import org.apache.log4j.Logger;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class AbstractChannelHandler implements ChannelHandler{

    private Logger logger = Logger.getLogger(AbstractChannelHandler.class);

    protected static final ExecutorService SHARED_EXECUTOR = Executors.newCachedThreadPool(new NamedThreadFactory("AbstractChannelHandler", true));

    protected final ExecutorService executor;

    public AbstractChannelHandler(){
        this.executor = Executors.newCachedThreadPool(new NamedThreadFactory("AbstractChannelHandler", true));
    }

    public void close() {
        try {
            if (executor != null) {
                executor.shutdown();
            }
        } catch (Throwable t) {
            logger.warn("fail to destroy thread pool of server: " + t.getMessage(), t);
        }
    }

    public ExecutorService getExecutorService() {
        return executor == null || executor.isShutdown() ? SHARED_EXECUTOR : executor;
    }
}
